package cn.zhy.filter;

import com.alibaba.fastjson.JSON;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class Login extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        //请求头获取uri
        String uri = request.getRequestURI();
        // 2.判断请求路径是否包含token，包含就不执行登录业务校验，所以返回false
        if (uri.endsWith("login") || uri.endsWith("register")){
            return false;
        }
        //如果不包含
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        HttpServletResponse response = RequestContext.getCurrentContext().getResponse();

        //判断是否有token，没有就阻止执行后面
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            //创建返回的对象
            Map map = new HashMap<>();
            map.put("code", 500);
            map.put("success", 200);
            map.put("message", "token出毛病了");
            //因为这里是json对象要转换成json字符串
            String s = JSON.toJSONString(map);
            try {
                response.setContentType("application/json;charset=utf8");
                //把返回对象写入respones
                response.getWriter().print(s);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //拦截
            //setSendZuulResponse这个方法-阻止filter后续执行  强行记忆
            RequestContext.getCurrentContext().setSendZuulResponse(false);

        }
        return null;
    }
}
